package com.msxt.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.msxt.annotation.IgnoreAuth;
import com.msxt.dto.StoreupEntity;
import com.msxt.result.R;
import com.msxt.service.StoreupService;
import com.msxt.utils.MPUtil;
import com.msxt.utils.PageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * 收藏表
 * 后端接口
 */
@Slf4j
@RestController
@RequestMapping("/storeup")
public class StoreupController {
    @Autowired
    private StoreupService storeupService;

    /**
     * 后端列表
     */
    @GetMapping("/page")
    public R page(@RequestParam Map<String, Object> params,
                  StoreupEntity storeup,
                  HttpServletRequest request) {
        // 从请求属性获取 role 和 userId
        Object roleObj = request.getAttribute("role");
        Object userIdObj = request.getAttribute("userId");

        // 添加空值检查
        if (roleObj != null && !"管理员".equals(roleObj.toString()) && userIdObj != null) {
            try {
                Long userId = Long.parseLong(userIdObj.toString());
                storeup.setUserid(userId);
            } catch (NumberFormatException e) {
                log.error("用户ID格式错误: {}", userIdObj);
            }
        }

        QueryWrapper<StoreupEntity> wrapper = new QueryWrapper<>();
        PageUtils page = storeupService.queryPage(params,
                MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(wrapper, storeup), params), params));
        return R.ok().put("data", page);
    }

    /**
     * 前端列表
     */
    @IgnoreAuth
    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> params,
                  StoreupEntity storeup,
                  HttpServletRequest request) {
        QueryWrapper<StoreupEntity> wrapper = new QueryWrapper<>();
        PageUtils page = storeupService.queryPage(params,
                MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(wrapper, storeup), params), params));
        return R.ok().put("data", page);
    }

    /**
     * 列表
     */
    @GetMapping("/lists")
    public R list(StoreupEntity storeup) {
        QueryWrapper<StoreupEntity> wrapper = new QueryWrapper<>();
        wrapper.allEq(MPUtil.allEQMapPre(storeup, "storeup"));
        return R.ok().put("data", storeupService.list(wrapper));
    }

    /**
     * 查询
     */
    @GetMapping("/query")
    public R query(StoreupEntity storeup) {
        QueryWrapper<StoreupEntity> wrapper = new QueryWrapper<>();
        wrapper.allEq(MPUtil.allEQMapPre(storeup, "storeup"));
        return R.ok("查询收藏表成功").put("data", storeupService.selectView(wrapper));
    }

    /**
     * 后端详情
     */
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        StoreupEntity storeup = storeupService.getById(id);
        return R.ok().put("data", storeup);
    }

    /**
     * 前端详情
     */
    @IgnoreAuth
    @GetMapping("/detail/{id}")
    public R detail(@PathVariable("id") Long id) {
        StoreupEntity storeup = storeupService.getById(id);
        return R.ok().put("data", storeup);
    }

    /**
     * 后端保存
     */
    @PostMapping("/save")
    public R save(@RequestBody StoreupEntity storeup,
                  HttpServletRequest request) {
        // 从请求属性获取 userId
        Object userIdObj = request.getAttribute("userId");
        if (userIdObj == null) {
            return R.error("用户未登录");
        }

        try {
            Long userId = Long.parseLong(userIdObj.toString());
            storeup.setId(new Date().getTime() + new Double(Math.floor(Math.random() * 1000)).longValue());
            storeup.setUserid(userId);
            storeupService.save(storeup);
            return R.ok();
        } catch (NumberFormatException e) {
            log.error("用户ID格式错误: {}", userIdObj);
            return R.error("无效的用户ID");
        }
    }


    /**
     * 前端保存
     */
    @PostMapping("/add")
    public R add(@RequestBody StoreupEntity storeup,
                 HttpServletRequest request) {
        storeup.setId(new Date().getTime() + new Double(Math.floor(Math.random() * 1000)).longValue());
        storeupService.save(storeup);
        return R.ok();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @Transactional
    public R update(@RequestBody StoreupEntity storeup,
                    HttpServletRequest request) {
        storeupService.updateById(storeup);
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    public R delete(@RequestBody Long[] ids) {
        storeupService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

    /**
     * 提醒接口
     */
    @GetMapping("/remind/{columnName}/{type}")
    public R remindCount(@PathVariable("columnName") String columnName,
                         HttpServletRequest request,
                         @PathVariable("type") String type,
                         @RequestParam Map<String, Object> map) {
        map.put("column", columnName);
        map.put("type", type);

        if ("2".equals(type)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar c = Calendar.getInstance();
            Date remindStartDate = null;
            Date remindEndDate = null;
            if (map.get("rem极indstart") != null) {
                Integer remindStart = Integer.parseInt(map.get("remindstart").toString());
                c.setTime(new Date());
                c.add(Calendar.DAY_OF_MONTH, remindStart);
                remindStartDate = c.getTime();
                map.put("remindstart", sdf.format(remindStartDate));
            }
            if (map.get("remindend") != null) {
                Integer remindEnd = Integer.parseInt(map.get("remindend").toString());
                c.setTime(new Date());
                c.add(Calendar.DAY_OF_MONTH, remindEnd);
                remindEndDate = c.getTime();
                map.put("remindend", sdf.format(remindEndDate));
            }
        }

        QueryWrapper<StoreupEntity> wrapper = new QueryWrapper<>();

        // 使用AND连接条件
        if (map.get("remindstart") != null || map.get("remindend") != null) {
            wrapper.and(w -> {
                if (map.get("remindstart") != null) {
                    w.ge(columnName, map.get("remindstart"));
                }
                if (map.get("remindend") != null) {
                    w.le(columnName, map.get("remindend"));
                }
            });
        }

        // 从请求属性获取 role 和 userId
        Object roleObj = request.getAttribute("role");
        Object userIdObj = request.getAttribute("userId");

        if (roleObj != null && !"管理员".equals(roleObj.toString()) && userIdObj != null) {
            try {
                Long userId = Long.parseLong(userIdObj.toString());
                wrapper.eq("userid", userId);
            } catch (NumberFormatException e) {
                log.error("用户ID格式错误: {}", userIdObj);
            }
        }

        long count = storeupService.count(wrapper);
        return R.ok().put("count", count);
    }
}